package cn.chengpengper.rpc.enhanced.loadbalancer.sourceip.hash;

import cn.chengpengper.rpc.loadbalancer.base.BaseEnhancedServiceLoadBalancer;
import cn.chengpengper.rpc.protocol.meta.ServiceMeta;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class SourceIpHashWeightServiceEnhancedLoadBalancer extends BaseEnhancedServiceLoadBalancer {

    @Override
    public ServiceMeta select(List<ServiceMeta> servers, int hashCode, String ip) {
        log.info("增强型基于权重的源IP地址Hash的负载均衡策略");
        servers = this.getWeightServiceMetaList(servers);
        if (servers == null || servers.isEmpty()) {
            return null;
        }
        //传入的IP地址为空，则默认返回第一个服务实例
        if (StringUtils.isEmpty(ip)) {
            return servers.get(0);
        }
        int resultHashCode = Math.abs(ip.hashCode() + hashCode);
        return servers.get(resultHashCode % servers.size());
    }
}
